package com.ruoyi.baseMain.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lark.oapi.Client;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.service.approval.v4.model.CreateInstanceReq;
import com.lark.oapi.service.approval.v4.model.CreateInstanceResp;
import com.lark.oapi.service.approval.v4.model.InstanceCreate;
import com.ruoyi.GetToken;
import com.ruoyi.baseMain.domain.bo.BaseCustomFeishuDto;
import com.ruoyi.baseMain.mapper.BasePolicyMapper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.dto.RoleDTO;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.baseMain.domain.bo.BaseCustomBo;
import com.ruoyi.baseMain.domain.vo.BaseCustomVo;
import com.ruoyi.baseMain.domain.BaseCustom;
import com.ruoyi.baseMain.mapper.BaseCustomMapper;
import com.ruoyi.baseMain.service.IBaseCustomService;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.Objects;

/**
 * 客户信息Service业务层处理
 *
 * @author linziheng
 * @date 2023-12-31
 */
@RequiredArgsConstructor
@Service
public class BaseCustomServiceImpl implements IBaseCustomService {

    private final BaseCustomMapper baseMapper;
    private final BasePolicyMapper basePolicyMapper;
    private final SysUserMapper sysUserMapper;
    private final SysDeptMapper sysDeptMapper;
    /**
     * 查询客户信息
     */
    @Override
    public BaseCustomVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }
    @Override
    public  int getWeekList(String date){
        return baseMapper.getWeekList(date);
    }

    @Override
    public int countCustom(){
        return baseMapper.countCustom();
    }

    /**
     * 查询客户信息列表
     */
    @Override
    public TableDataInfo<BaseCustomVo> queryPageList(BaseCustomBo bo, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        String user = "";
        for (RoleDTO role : loginUser.getRoles()) {
            if(1719534201567039490L == role.getRoleId() || 1L== role.getRoleId() || 1720783927643512833L == role.getRoleId()
                || 1720783977803194369L == role.getRoleId()|| 1741717746987237377L == role.getRoleId()|| 1750333840374910977L == role.getRoleId()){
                user = "admin";
                break;
            }
        }
        if(!"admin".equals(user)){
            bo.setSaleUserName(loginUser.getNickName());
        }
        SysUser uuu = sysUserMapper.selectUserById(loginUser.getUserId());
        SysDept sysDept = new SysDept();
        if(!"admin".equals(user)){
            sysDept = sysDeptMapper.findDeptByLeader(uuu.getRemark());
            if(!Objects.isNull(sysDept)){
                //根据id 查询部门名称
                bo.setBusinessUnitName(sysDept.getDeptName());
                bo.setSaleUserName(null);
            }else{
                bo.setSaleUserName(uuu.getNickName());
            }
            //业务中泰看所有
            if(uuu.getDeptId()==1811377323661430787L){
                bo.setBusinessUnitName(null);
                bo.setSaleUserName(null);
            }
        }

        LambdaQueryWrapper<BaseCustom> lqw = buildQueryWrapper(bo);
        Page<BaseCustomVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询客户信息列表
     */
    @Override
    public List<BaseCustomVo> queryList(BaseCustomBo bo) {
        bo.setStatus("1");
        LambdaQueryWrapper<BaseCustom> lqw = buildQueryWrapper(bo);
        List<BaseCustomVo> list= baseMapper.selectVoList(lqw);
        return list;
    }

    private LambdaQueryWrapper<BaseCustom> buildQueryWrapper(BaseCustomBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BaseCustom> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getNickName()), BaseCustom::getNickName, bo.getNickName());
        lqw.like(StringUtils.isNotBlank(bo.getRemark()), BaseCustom::getRemark, bo.getRemark());
        lqw.eq(StringUtils.isNotBlank(bo.getChannel()), BaseCustom::getChannel, bo.getChannel());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), BaseCustom::getStatus, bo.getStatus());

        lqw.eq(StringUtils.isNotBlank(bo.getCooperateType()), BaseCustom::getCooperateType, bo.getCooperateType());
        lqw.eq(StringUtils.isNotBlank(bo.getPayType()), BaseCustom::getPayType, bo.getPayType());
        lqw.eq(StringUtils.isNotBlank(bo.getAparty()), BaseCustom::getAparty, bo.getAparty());
        lqw.eq(StringUtils.isNotBlank(bo.getBparty()), BaseCustom::getBparty, bo.getBparty());
        lqw.eq(StringUtils.isNotBlank(bo.getBusinessUnit()), BaseCustom::getBusinessUnit, bo.getBusinessUnit());
        lqw.eq(StringUtils.isNotBlank(bo.getBusinessUnitName()), BaseCustom::getBusinessUnitName, bo.getBusinessUnitName());
        lqw.eq(StringUtils.isNotBlank(bo.getSaleUser()), BaseCustom::getSaleUser, bo.getSaleUser());
        lqw.eq(StringUtils.isNotBlank(bo.getSaleUserName()), BaseCustom::getSaleUserName, bo.getSaleUserName());
        lqw.orderByDesc(BaseCustom::getCreateTime);
        return lqw;
    }

    /**
     * 新增客户信息
     */
    @Override
    public R insertByBo(BaseCustomBo bo) throws Exception {

        BaseCustom add = BeanUtil.toBean(bo, BaseCustom.class);
        add.setStatus("2");
        QueryWrapper<BaseCustom> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("contract_no", bo.getContractNo());
        Long sum = baseMapper.selectCount(queryWrapper);
        boolean flag = false;
        if(sum>0){
           return R.fail("合同号重复");
        }
        if (bo.getSigns() == null) {
            bo.setSigns("未签署");
        }
        R r = instancesCreate(bo,"EFC68385-B389-445D-BB6F-503D555D7257");
        if(r.getCode() == 200) {
            add.setInstanceCode(r.getMsg());
            flag = baseMapper.insert(add) > 0;
            return R.ok();

        }else{
            return R.fail(r);

        }


    }
    public R instancesCreate(BaseCustomBo bo, String inten) throws Exception {
        GetToken getToken = new GetToken();
        Client client = Client.newBuilder(getToken.appId, getToken.appSecret).build();

        JSONArray ja = new JSONArray();
        JSONObject jb1 = new JSONObject();
        jb1.set("id","nickName");
        jb1.set("type","input");
        jb1.set("value",bo.getNickName());
        ja.add(jb1);

        JSONObject jb2 = new JSONObject();
        jb2.set("id","aparty");
        jb2.set("type","input");
        jb2.set("value",bo.getAparty());
        ja.add(jb2);

        JSONObject jb3 = new JSONObject();
        jb3.set("id","bparty");
        jb3.set("type","input");
        jb3.set("value",bo.getBparty());
        ja.add(jb3);

        JSONObject jb4 = new JSONObject();
        jb4.set("id","contractNo");
        jb4.set("type","input");
        jb4.set("value",bo.getContractNo());
        ja.add(jb4);

        JSONObject jb5 = new JSONObject();
        jb5.set("id","channel");
        jb5.set("type","input");
        jb5.set("value",bo.getChannel());
        ja.add(jb5);

        JSONObject jb6 = new JSONObject();
        jb6.set("id","cooperateType");
        jb6.set("type","input");
        jb6.set("value",bo.getCooperateType());
        ja.add(jb6);

        JSONObject jb7 = new JSONObject();
        jb7.set("id","payType");
        jb7.set("type","input");
        if("对私付款".equals(bo.getPayType())){
            jb7.set("value","非公支付");
        }else{
            jb7.set("value",bo.getPayType());
        }

        ja.add(jb7);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String contractStartTime = sdf.format(bo.getContractStartTime());

        JSONObject jb8 = new JSONObject();
        jb8.set("id","contractStartTime");
        jb8.set("type","input");
        jb8.set("value",contractStartTime);
        ja.add(jb8);
        SimpleDateFormat sdf1= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String contractEndTime = sdf1.format(bo.getContractEndTime());

        JSONObject jb9 = new JSONObject();
        jb9.set("id","contractEndTime");
        jb9.set("type","input");
        jb9.set("value",contractEndTime);
        ja.add(jb9);


        JSONObject jb10 = new JSONObject();
        jb10.set("id","saleUserName");
        jb10.set("type","input");
        jb10.set("value",bo.getSaleUserName());
        ja.add(jb10);



        JSONObject jb11 = new JSONObject();
        jb11.set("id","businessUnitName");
        jb11.set("type","input");
        jb11.set("value",bo.getBusinessUnitName());
        ja.add(jb11);

        JSONObject jb12 = new JSONObject();
        jb12.set("id","sign");
        jb12.set("type","input");
        jb12.set("value",bo.getSigns());
        ja.add(jb12);

        JSONObject jb13 = new JSONObject();
        jb13.set("id","customType");
        jb13.set("type","input");
        jb13.set("value",bo.getCustomType());
        ja.add(jb13);


        String from = ja.toString();
        // 创建请求对象
        String openId = LoginHelper.getLoginUser().getFeishuId();
        CreateInstanceReq req = CreateInstanceReq.newBuilder()
            .instanceCreate(InstanceCreate.newBuilder()
                .approvalCode(inten)
                .openId(openId)
                .form(from)
                .build())
            .build();

        // 发起请求
        CreateInstanceResp resp = client.approval().v4().instance().create(req);

        // 处理服务端错误
        if (!resp.success()) {
            System.out.println(String.format("code:%s,msg:%s,reqId:%s"
                , resp.getCode(), resp.getMsg(), resp.getRequestId()));
            return R.fail();
        }

        // 业务数据处理
        System.out.println(Jsons.DEFAULT.toJson(resp.getData()));

        return R.ok(resp.getData().getInstanceCode());
    }

    /**
     * 修改客户信息
     */
    @Override
    public Boolean updateByBo(BaseCustomBo bo) {
        BaseCustom update = BeanUtil.toBean(bo, BaseCustom.class);
        validEntityBeforeSave(update);
        //修改后同步修改引用该客户id的所有客户政策
        basePolicyMapper.updateAllByCustomId(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BaseCustom entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除客户信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
    @Override
    public String getSaleUserByCustomName(String customName){
        return baseMapper.getSaleUserByCustomName(customName) ;
    }
    @Override
    public List<BaseCustomBo> queryListInstanceIdIsNotNull(){
        return baseMapper.queryListInstanceIdIsNotNull() ;
    }
    @Override
    public void signUpdateDo(Long id) throws Exception {
        BaseCustomVo baseCustomVo = baseMapper.selectVoById(id);
        BaseCustomBo bo = BeanUtil.toBean(baseCustomVo, BaseCustomBo.class);
        bo.setSigns("审核中");
        R r = instancesCreate(bo,"FE4288A6-814A-4364-8D94-29CF716EAE91");
        if(r.getCode() == 200) {
            bo.setInstanceCode(r.getMsg());
            BaseCustom add = BeanUtil.toBean(bo, BaseCustom.class);
            baseMapper.updateById(add);
        }

    }
    @Override
    public List<BaseCustomFeishuDto> queryListToFeishu() {
            return baseMapper.queryListToFeishu() ;
    }
    @Override
    public List<BaseCustomFeishuDto> getMedium() {
            return baseMapper.getMedium() ;
    }
}
